if(typeof(ko.extensions.webos.command) == 'undefined')
    ko.extensions.webos.command = {};

ko.extensions.webos.command.appendConsole = function(msg)
{
    if(document.getElementById("webosCommandOutputText").value == "")
        document.getElementById("webosCommandOutputText").value += msg;
    else
        document.getElementById("webosCommandOutputText").value += "\n" + msg;
};

ko.extensions.webos.command.clearConsole = function()
{
    document.getElementById("webosCommandOutputText").value = "";
};

ko.extensions.webos.command.truncateConsole = function(msg)
{
    document.getElementById("webosCommandOutputText").value = msg;
};

ko.extensions.webos.command.focus = function()
{
    if(document.getElementById("webosRunText").value == "Enter a command and press enter"
       && document.getElementById("webosRunText").readOnly == false)
    {
        document.getElementById("webosRunText").style.color = "#000000";
        document.getElementById("webosRunText").value = "";
    }
    else if(document.getElementById("webosRunText").value == "Enter a command and press enter"
            && document.getElementById("webosRunText").readOnly == true)
    {
        document.getElementById("webosCommandOutputText").focus();
    }
};

ko.extensions.webos.command.blur = function()
{
    if(document.getElementById("webosRunText").value == "")
    {
        document.getElementById("webosRunText").style.color = "#666666";
        document.getElementById("webosRunText").value = "Enter a command and press enter";
    }
};

ko.extensions.webos.command.iconStatic = function()
{
    document.getElementById("webosRunText").className = "webosRunText-static";
    document.getElementById("webosRunText").readOnly = false;
    
};

ko.extensions.webos.command.iconAnimate = function()
{
    document.getElementById("webosRunText").className = "webosRunText-animate";
    document.getElementById("webosRunText").readOnly = true;
};

ko.extensions.webos.command.iconDisabled = function()
{
    document.getElementById("webosRunText").className = "webosRunText-disabled";
    document.getElementById("webosRunText").readOnly = true;
    document.getElementById("webosRunText").style.backgroundColor = "#F1F1F1";
    document.getElementById("webosRunText").value = "Enter a command and press enter"
    document.getElementById("webosRunText").blur();
};

ko.extensions.webos.command.iconError = function()
{
    document.getElementById("webosRunText").className = "webosRunText-error";
    setTimeout(function()
    {
        document.getElementById("webosRunText").className = "webosRunText-static";
    }, 2000);
    document.getElementById("webosRunText").readOnly = false;
};

ko.extensions.webos.command.time = 0;

ko.extensions.webos.command.execute = function(cmd)
{
    ko.extensions.webos.command.iconAnimate();
    if(cmd.match(/^([a-zA-Z]*)(?:\s*)?(.*?)$/i) != null)
    {
        cmd_full = cmd.match(/^([a-zA-Z]*)(?:\s*)?(.*?)$/i)[0];
        cmd_name = cmd.match(/^([a-zA-Z]*)(?:\s*)?(.*?)$/i)[1];
        cmd_args = cmd.match(/^([a-zA-Z]*)(?:\s*)?(.*?)$/i)[2];
    }
    else
    {
        cmd_name = "none";
    }
    switch(cmd_name)
    {
        case "list":
            if(cmd_args == "")
                c = 'cd /\n';
            else
                c = 'cd ' + cmd_args + "\n";
            alert(c);
            ko.extensions.webos.palm.emulatorSSH(c, "", function()
            {
                if(this.success)
                {
                    ko.extensions.webos.command.truncateConsole(this.output);
                    ko.extensions.webos.command.iconStatic();
                }
                else
                {
                    ko.extensions.webos.command.truncateConsole("Could not connect to Emulator or Command Failed");
                    ko.extensions.webos.command.iconError();
                }
            });
            break;
        case "ssh":
            if(cmd_args == "-help")
            {
                var msg = "Be very careful everything after ssh is ran as a SSH command, use && to combine commands till it is developed more, and \"help\" to see some future commands.\n";
                msg += "ssh echo Hello World\n";
                msg += "ssh cd /&&ls -la";
                ko.extensions.webos.command.truncateConsole(msg);
                ko.extensions.webos.command.iconStatic();
            }
            else
            {
                ko.extensions.webos.palm.emulatorSSH(cmd_args + "\n", "", function()
                {
                    if(this.success)
                    {
                        if(this.output == "")
                            ko.extensions.webos.command.truncateConsole("[Empty]");
                        else
                            ko.extensions.webos.command.truncateConsole(this.output);
                        ko.extensions.webos.command.iconStatic();
                    }
                    else
                    {
                        ko.extensions.webos.command.truncateConsole("Could not connect to Emulator");
                        ko.extensions.webos.command.iconError();
                    }
                });
            }
            break;
        case "log":
            if(cmd_args == "-help")
            {
                var msg = "This command is still under development and does not currently do real time.\n";
                msg += "log\n";
                msg += "log com.domain.app\n";
                msg += "log clear";
                ko.extensions.webos.command.truncateConsole(msg);
                ko.extensions.webos.command.iconStatic();
            }
            else if(cmd_args == "active" || cmd_args == "" || cmd_args.match(/^([a-zA-Z0-9\.]+?)\.([a-zA-Z0-9\.]+?)\.([a-zA-Z0-9\.]+?)$/) != null)
            {
                var id = ko.extensions.webos.project.info().id;
                if(cmd_args.match(/^([a-zA-Z0-9\.]+?)\.([a-zA-Z0-9\.]+?)\.([a-zA-Z0-9\.]+?)$/) != null)
                    id = cmd_args;
                ko.extensions.webos.palm.emulatorSSH("tail -f /var/log/messages\n", "", function()
                {
                    if(this.success)
                    {
                        if(this.output == "")
                        {
                            ko.extensions.webos.command.truncateConsole("[Empty]");
                        }
                        else
                        {
                            ko.extensions.webos.command.clearConsole();
                            var str = this.output;
                            var matched = true;
                            var a = str.match(/\d+\-\d+\-\d+T\d+:\d+:\d+.\d+Z \[\d+\] (qemux86) (user).(info|crit|err|warning) [\w]+: {\w+} ([a-zA-Z0-9.]+): ([=>]+|\w+:) (.+), file:\/\/\/var\/usr\/palm\/applications\/\4\/([a-zA-Z0-9.]+):0/g);
                            for(var b in a)
                            {
                                var na = a[b].match(/\d+\-\d+\-\d+T\d+:\d+:\d+.\d+Z \[\d+\] (qemux86) (user).(info|crit|err|warning) [\w]+: {\w+} ([a-zA-Z0-9.]+): ([=>]+|\w+:) (.+), file:\/\/\/var\/usr\/palm\/applications\/\4\/([a-zA-Z0-9.]+):0/);
                                if(id == na[4])
                                {
                                    matched = false;
                                    ko.extensions.webos.command.appendConsole(na[3] + ": " + na[6]);
                                }
                            }
                            if(matched)
                            {
                                ko.extensions.webos.command.appendConsole("[Empty: Run the \"log full\" command for the full log file]");
                            }
                        }
                        ko.extensions.webos.command.iconStatic();
                    }
                    else
                    {
                        ko.extensions.webos.command.truncateConsole("Could not connect to Emulator");
                        ko.extensions.webos.command.iconError();
                    }
                });
            }
            else if(cmd_args == "clear")
            {
                ko.extensions.webos.palm.emulatorSSH("rm /var/log/messages\n", "", function()
                {
                    if(this.success)
                    {
                        ko.extensions.webos.palm.emulatorSSH("tail -f /var/log/messages\n", "", function()
                        {
                            if(this.success)
                            {
                                if(this.output == "")
                                    ko.extensions.webos.command.truncateConsole("[Empty]");
                                else
                                    ko.extensions.webos.command.truncateConsole(this.output);
                                ko.extensions.webos.command.iconStatic();
                            }
                            else
                            {
                                ko.extensions.webos.command.truncateConsole("Could not connect to Emulator");
                                ko.extensions.webos.command.iconError();
                            }
                        });
                    }
                    else
                    {
                        ko.extensions.webos.command.truncateConsole("Could not connect to Emulator");
                        ko.extensions.webos.command.iconError();
                    }
                });
            }
            else if(cmd_args == "full")
            {
                ko.extensions.webos.palm.emulatorSSH("tail -f /var/log/messages\n", "", function()
                {
                    if(this.success)
                    {
                        if(this.output == "")
                            ko.extensions.webos.command.truncateConsole("[Empty]");
                        else
                            ko.extensions.webos.command.truncateConsole(this.output);
                        ko.extensions.webos.command.iconStatic();
                    }
                    else
                    {
                        ko.extensions.webos.command.truncateConsole("Could not connect to Emulator");
                        ko.extensions.webos.command.iconError();
                    }
                });
            }
            else
            {
                ko.extensions.webos.command.truncateConsole("[Unknown command run \"log -help\" to get a list of commands]");
                ko.extensions.webos.command.iconError();
            }
            break;
        case "call":
            
            ko.extensions.webos.command.iconStatic();
            break;
        case "sms":
            
            ko.extensions.webos.command.iconStatic();
            break;
        case "opname":
            
            ko.extensions.webos.command.iconStatic();
            break;
        case "gps":
            
            ko.extensions.webos.command.iconStatic();
            break;
        case "preware":
            alert("Command Line Tool Coming Soon");
            ko.extensions.webos.command.iconStatic();
            break;
        case "jslint":
            var msg = "";
            if(cmd_args == "-help")
            {
                msg += "jslint -help\n";
                msg += 'jslint log 1\n';
                msg += 'jslint log 0\n';
                ko.extensions.webos.command.truncateConsole(msg);
            }
            else if(cmd_args == "log 1")
            {
                msg += "Logging Enabled for JSLint\n";
                ko.extensions.webos.jslint.log = true;
            }
            else if(cmd_args == "log 0")
            {
                msg += "Logging Disabled for JSLint\n";
                ko.extensions.webos.jslint.log = false;
            }
            else
            {
                msg += "Unknown Command. Use the \"jslint -help\" command to view a list of supported commands.\n";
            }
            ko.extensions.webos.command.truncateConsole(msg);
            ko.extensions.webos.command.iconStatic();
            break;
        case "todo":
            var msg = "";
            if(cmd_args == "-help")
            {
                msg += "todo -help\n";
                msg += 'todo log 1\n';
                msg += 'todo log 0\n';
                ko.extensions.webos.command.truncateConsole(msg);
            }
            else if(cmd_args == "log 1")
            {
                msg += "Logging Enabled for ToDo\n";
                ko.extensions.webos.todo.log = true;
            }
            else if(cmd_args == "log 0")
            {
                msg += "Logging Disabled for ToDo\n";
                ko.extensions.webos.todo.log = false;
            }
            else
            {
                msg += "Unknown Command. Use the \"jslint -help\" command to view a list of supported commands.\n";
            }
            ko.extensions.webos.command.truncateConsole(msg);
            ko.extensions.webos.command.iconStatic();
            break;
        case "ajax":
            var d = new Date();
            ko.extensions.webos.command.time = d.getTime();
            var msg = "";
            if(cmd_args == "-help")
            {
                msg += "ajax -help\n";
                msg += 'ajax http://domain.com/ post {param1:"value1",param2:"value2"}\n';
                ko.extensions.webos.command.truncateConsole(msg);
                ko.extensions.webos.command.iconStatic();
            }
            else if(cmd_args.match(/^(.*?)\s+(post|get)\s+\{(.*?)\}$/i) != null)
            {
                var parts = cmd_args.match(/^(.*?)\s+(post|get)\s+\{(.*?)\}$/i);
                var url = parts[1];
                var method = parts[2];
                var parameters = parts[3];
                eval("parameters = {" + parameters + "}");
                var req = new XMLHttpRequest();
                req.onreadystatechange = function()
                {
                    if(req.readyState == 4)
                    {
                        if(req.status == 200)
                        {
                            var d = new Date();
                            var ms = d.getTime() - ko.extensions.webos.command.time;
                            ko.extensions.webos.command.truncateConsole("Results(" + ms + "ms):\n" + req.responseText + "\n");
                            ko.extensions.webos.command.iconStatic();
                        }
                        else
                        {
                            ko.extensions.webos.command.truncateConsole(req.status + ": " + req.statusText + "\n");
                            ko.extensions.webos.command.iconStatic();
                        }
                    }
                };
                if(method == "post")
                {
                    req.open("POST", url, true);
                }
                else
                {
                    req.open("GET", url, true);
                }
                var param = "";
                var params = false;
                for(i in parameters)
                {
                    if(!params)
                    {
                        param += i + "=" + escape(parameters[i]);
                        params = true;
                    }
                    else
                    {
                        param += "&" + i + "=" + escape(parameters[i]);
                    }
                }
                req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                //req.setRequestHeader("Connection", "close");
                if(params)
                {
                    req.setRequestHeader("Content-length", param.length);
                    req.send(param);
                }
                else
                {
                    req.setRequestHeader("Connection", "close");
                    req.send(null);
                }
            }
            else
            {
                msg += "Unknown Command. Use the \"ajax -help\" command to view a list of supported commands.\n";
                ko.extensions.webos.command.iconStatic();
            }
            ko.extensions.webos.command.truncateConsole(msg);
            break;
        case "help":
            var msg = "ssh <command>\n";
            msg += 'log\n';
            msg += 'todo\n';
            msg += 'jslint\n';
            msg += 'call <number> (coming soon)\n';
            msg += 'sms <number> <message> (coming soon)\n';
            msg += 'gps <lat>,<long>[,<sec>] [repeat] (coming soon)\n';
            msg += 'operatorname <name> (coming soon)\n';
            msg += 'list <path> (coming soon)\n';
            ko.extensions.webos.command.truncateConsole(msg);
            ko.extensions.webos.command.iconStatic();
            break;
        case "clear":
            ko.extensions.webos.command.truncateConsole("");
            ko.extensions.webos.command.iconStatic();
            break;
        default:
            ko.extensions.webos.command.iconError();
            ko.extensions.webos.command.truncateConsole('Unknown Command: "' + cmd_name + '"');
    }
    document.getElementById("webosRunText").focus();
    document.getElementById("webosRunText").select();
    ko.extensions.webos.view("command");
};

ko.extensions.webos.command.keypress = function(e)
{
    if(e.keyCode == 13)
        if(document.getElementById("webosRunText").readOnly != true)
            ko.extensions.webos.command.execute(document.getElementById("webosRunText").value);
};